<!-- eslint-disable eqeqeq -->
<!--
  采购订单管理
 -->

<template>
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="51"
        :add-active="addActive"
        :del-active="delActive"
        :edit-active="editActive"
        :has-cancel="false"
        :has-save="false"
        :has-edit="false"
        :has-del="false"
        @add="add"
        @cancel="cancel('formData')"
        @edit="edit"
        @del="del"
        @save="save"
      />
    </template>
    <template v-slot:tab-select>
      <SelectButton :buttonselectlist="buttonselectlist" @nowselectbuttonindex="batchstaumet" />
    </template>
    <template v-slot:search-box>
      <SearchBox @search="search">
        <div v-if="curTabIndex == 0" class="common-search-item">
          <div class="label">关联采购订单编号:</div>
          <div class="input">
            <el-select v-model="searchInfo.orderNo" placeholder="请选择" filterable clearable />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库单:</span>
          <div class="input">
            <el-input v-model="searchInfo.purchaserName" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">接收人:</span>
          <div class="input">
            <el-input v-model="searchInfo.personNo" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库仓库:</span>
          <div class="input">
            <el-input v-model="searchInfo.warehouseNo" />
          </div>
        </div>
        <div class="common-search-item">
          <span class="label">入库日期:</span>
          <div class="input">
            <StartTimeEndTimeSelectionBox @startVal="startVal" @endVal="endVal" />
          </div>
        </div>
      </SearchBox>
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        :data="tableData"
        stripe
        border
        height="calc(100% - 50px)"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="warehousingOrderNo" label="入库单号" min-width="100" />
        <el-table-column prop="warehouseName" label="入库仓库" />
        <el-table-column prop="personName" label="接收人" />
        <el-table-column prop="warehousingDate" label="入库日期" min-width="100" />
        <el-table-column prop="supplyProducts" label="入库图片">
          <template v-if="scope.row.warehousingOrderNo" slot-scope="scope">
            <el-button
              v-if="scope.row.pictureNoList.length"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="showimgmet(scope.row)"
            >查看</el-button>
            <span v-else>暂无</span>
          </template>
        </el-table-column>
        <el-table-column width="200" label="入库产品">
          <template v-if="scope.row.warehousingOrderNo" slot-scope="scope">
            <el-button type="text" class="text-btn-cursor" @click="handledbCheck(scope.row)">
              <i class="el-icon-view"></i> 查看
            </el-button>
          </template>
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template v-if="scope.row.warehousingOrderNo" slot-scope="scope">
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <!-- 展示图片 -->
      <el-dialog title="执照图片" :visible.sync="isshowimg" width="30%">
        <img :src="nowimgurl" width="100%" height="auto" />
      </el-dialog>
      <!-- 来料入库 -->
      <el-dialog
        :title="titleText + '入库信息'"
        :visible.sync="dialogFormVisible"
        :before-close="handleClose"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="采购订单:" class="w50p" prop="purchaseOrderNo">
            <el-select
              v-model="formData.purchaseOrderNo"
              :disabled="!canInput"
              clearable
              filterable
              @change="getProductList"
            >
              <el-option v-for="item in sellOrderLIst" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
          <el-form-item label="入库日期:" class="w50p" prop="deliveryTime">
            <el-date-picker
              v-model="formData.warehousingDate"
              type="date"
              placeholder="选择时间"
              :disabled="!canInput"
              value-format="timestamp"
            />
          </el-form-item>

          <el-form-item label="接收人:" class="w100p" prop="personNo">
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important"
              prop="departmentNo"
            >
              <el-select v-model="formData.departmentNo" clearable @change="getPostList">
                <el-option
                  v-for="(item, index) in departmentList"
                  :key="index.departmentNo"
                  :label="item.departmentName"
                  :value="item.departmentNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="postNo"
            >
              <el-select v-model="formData.postNo" clearable @change="getStaffList">
                <el-option
                  v-for="(item, index) in postList"
                  :key="index.postNo"
                  :label="item.postName"
                  :value="item.postNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="personNo"
            >
              <el-select v-model="formData.personNo" clearable>
                <el-option
                  v-for="(item, index) in staffList"
                  :key="index.personNo"
                  :label="item.person.name"
                  :value="item.personNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="入库产品类型:" class="w50p" prop="warehousingProductType">
            <el-select
              v-model="formData.warehousingProductType"
              :disabled="!canInput"
              clearable
              filterable
              @change="getWarehouseList"
            >
              <el-option
                v-for="item in warehousingProductTypeList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="入库仓库:" class="w50p" prop="warehouseNo">
            <el-select v-model="formData.warehouseNo" :disabled="!canInput" clearable filterable>
              <el-option
                v-for="item in warehouseList"
                :key="item.warehouseNo"
                :label="item.warehouseName"
                :value="item.warehouseNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" class="w50p" prop="remarks">
            <el-input v-model="formData.remarks" :disabled="!canInput" clearable />
          </el-form-item>
          <el-form-item label="入库图片:" prop="pictureNo" class="w100p">
            <ele-upload-image
              v-model="image"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :action="ImageUrl()"
            />
          </el-form-item>
          <el-row>
            <h4 class="total-price">
              <span>采购物品明细:</span>
              <span>采购总金额:{{ totalPrice }}元</span>
            </h4>
            <el-table
              ref="rightTableData"
              :data="rightTableData"
              tooltip-effect="dark"
              highlight-current-row
              border
              stripe
              class="rightTableData"
              @selection-change="selectRow"
            >
              <el-table-column type="index" label="序号" width="50" />
              <el-table-column label="物品名称" prop="goodsName" align="center" min-width="120" />
              <el-table-column label="规格" prop="specification" />
              <el-table-column label="型号" prop="model" />
              <el-table-column label="单价" prop="unitPrice" />
              <el-table-column label="入库数量" prop="quantity" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantity" />
                </template>
              </el-table-column>
              <el-table-column label="单位" min-width="75" prop="unitName" />
              <el-table-column label="优惠金额" prop="favorablePrice" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.favorablePrice" />
                </template>
              </el-table-column>
              <el-table-column label="物品总价" prop="totalPriceItem" min-width="95" />
              <template slot="empty">
                <div>请添加数据</div>
              </template>
            </el-table>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <!-- 自行入库 -->
      <el-dialog
        :title="titleText + '入库信息'"
        :visible.sync="dialogFormVisibleTwo"
        :before-close="handleClose"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formDataTwo"
          :rules="rulesTwo"
          class="el-form"
        >
          <el-form-item label="接收人:" class="w100p" prop="personNo">
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important"
              prop="departmentNo"
            >
              <el-select v-model="formDataTwo.departmentNo" clearable @change="getPostList">
                <el-option
                  v-for="(item, index) in departmentList"
                  :key="index.departmentNo"
                  :label="item.departmentName"
                  :value="item.departmentNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="postNo"
            >
              <el-select v-model="formDataTwo.postNo" clearable @change="getStaffList">
                <el-option
                  v-for="(item, index) in postList"
                  :key="index.postNo"
                  :label="item.postName"
                  :value="item.postNo"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              class="w100p"
              style="width: calc(33% - 20px) !important; padding-left: 0 !important; margin-left: 30px"
              prop="personNo"
            >
              <el-select v-model="formDataTwo.personNo" clearable>
                <el-option
                  v-for="(item, index) in staffList"
                  :key="index.personNo"
                  :label="item.person.name"
                  :value="item.personNo"
                />
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item label="入库日期:" class="w50p" prop="warehousingDate">
            <el-date-picker
              v-model="formDataTwo.warehousingDate"
              type="date"
              placeholder="选择时间"
              :disabled="!canInput"
              value-format="timestamp"
            />
          </el-form-item>
          <el-form-item label="入库产品类型:" class="w50p" prop="warehousingProductType">
            <el-select
              v-model="formDataTwo.warehousingProductType"
              :disabled="!canInput"
              clearable
              filterable
              @change="getGoodsList"
            >
              <el-option
                v-for="item in warehousingProductTypeList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="入库来源:" class="w50p" prop="warehousingSource">
            <el-select
              v-model="formDataTwo.warehousingSource"
              :disabled="!canInput"
              clearable
              filterable
            >
              <el-option
                v-for="item in warehousingSourceList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注:" class="w50p" prop="remarks">
            <el-input v-model="formDataTwo.remarks" :disabled="!canInput" clearable />
          </el-form-item>
          <el-form-item label="入库图片:" prop="pictureNo" class="w100p">
            <ele-upload-image
              v-model="image"
              :response-fn="handleResponse"
              :before-remove="handleRemove"
              :headers="headers"
              :action="ImageUrl()"
            />
          </el-form-item>
          <el-row>
            <h4 class="total-price">
              <span>采购物品明细:</span>
              <span>采购总金额:{{ totalPrice }}元</span>
            </h4>
            <el-table
              ref="rightTableData"
              :data="rightTableData"
              tooltip-effect="dark"
              highlight-current-row
              border
              stripe
              class="rightTableData"
              @selection-change="selectRow"
            >
              <el-table-column type="index" label="序号" width="50" />
              <el-table-column label="物品名称" prop="goodsNo" align="center" min-width="120">
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.goodsNo"
                    filterable
                    clearable
                    @change="tableAgriMate(scope)"
                  >
                    <el-option
                      v-for="(item,index) of goodsList"
                      :key="index"
                      :label="item.productName || item.materialName"
                      :value="item.productNo || item.materialNo"
                    />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="规格" prop="specification" />
              <el-table-column label="型号" prop="model" />
              <el-table-column label="单价" prop="unitPrice">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.unitPrice" />
                </template>
              </el-table-column>
              <el-table-column label="入库数量" prop="quantity" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.quantity" />
                </template>
              </el-table-column>
              <el-table-column label="单位" min-width="75" prop="unitName" />
              <el-table-column label="优惠金额" prop="favorablePrice" min-width="95">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.favorablePrice" />
                </template>
              </el-table-column>
              <el-table-column label="物品总价" prop="totalPriceItem" min-width="95" />
              <template slot="empty">
                <div>请添加数据</div>
              </template>
            </el-table>
          </el-row>
          <el-row>
            <el-button
              type="info"
              plain
              :disabled="!canInput"
              icon="el-icon-circle-plus-outline"
              class="addInfo"
              @click="addButInfo"
            >添加</el-button>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancelTwo('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
      <!-- 入库产品 -->
      <el-dialog title="详细信息" :visible.sync="purchaseVisible" width="60%" class="purchase">
        <el-row>
          <h4 class="total-price">
            <span>采购物品明细:</span>
            <span>采购总金额:{{ totalPrice }}元</span>
          </h4>
          <el-table
            ref="rightTableData"
            :data="rightTableData"
            tooltip-effect="dark"
            highlight-current-row
            border
            stripe
            class="rightTableData"
            @selection-change="selectRow"
          >
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column label="物品名称" prop="goodsName" align="center" min-width="120" />
            <el-table-column label="规格" prop="specification">
              <template slot-scope="scope">
                {{ scope.row.specification }} {{ scope.row.perSpecUnitName }}
                <span
                  v-if="scope.row.perSpecUnitName&&scope.row.unitName"
                >/</span>
                {{ scope.row.unitName }}
              </template>
            </el-table-column>
            <el-table-column label="型号" prop="model" />
            <el-table-column label="单价" prop="unitPrice" />
            <el-table-column label="入库数量" prop="quantity" min-width="95" />
            <el-table-column label="单位" min-width="75" prop="unitName" />
            <el-table-column label="优惠金额" prop="favorablePrice" min-width="95" />
            <el-table-column label="物品总价" prop="totalPriceItem" min-width="95" />
            <!-- <el-table-column label="操作" min-width="80">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color:red;text-decoration: underline;"
                  :disabled="!canInput"
                  size="small"
                  @click.native.prevent="
                    deleteRow(scope.$index, rightTableData)
                  "
                >
                  删除
                </el-button>
              </template>
            </el-table-column>-->
            <template slot="empty">
              <div>请添加数据</div>
            </template>
          </el-table>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button class="zh-button-two" type="primary" @click="purchaseVisible = false">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import SearchBox from "@/components/SearchBox";
import { mymixin } from "@/utils/mixin";
import StartTimeEndTimeSelectionBox from "@/components/StartTimeEndTimeSelectionBox";
// import baseQuery from "@/api/digital-operation/base"
import SelectButton from "@/components/selectbutton/index.vue";
import warehouseInventory from "@/api/digital-operation/warehouse-inventory";
import purchaseOrderManage from "@/api/digital-operation/purchase-manage/purchase-order-manage";
import warehouseManage from "@/api/basic-info-manage/warehouse-manage";
import productManage from "@/api/basic-info-manage/product-manage";
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
import baseURL from "@/api/baseURL";
export default {
  // eslint-disable-next-line vue/name-property-casing
  name: "material-in",
  components: {
    BaseMainSlot,
    ActionBar,
    Pagination,
    StartTimeEndTimeSelectionBox,
    SearchBox,
    SelectButton
  },
  mixins: [mymixin],
  data() {
    return {
      nowimgurl: null,
      isshowimg: false,
      image: null,
      searchInfo: {},
      // 名称
      name: "",
      nameList: [],
      price: "",
      number: "",
      // 采购物品
      goodsId: "",
      goodsList: [],
      unitName: "",
      rulesTime: "",
      // 人員名稱
      purchaser: "",
      // 供應商名稱
      supplierId: "",
      totalPrice: 0,
      // 采购订单名称
      orderNumber: "",
      agriculturalMaterialName: "",
      StaffData: [],
      // 采购部门列表
      supplierList: [],
      paramNamelist: [],
      selectlistRow: [],
      salseProductsName: [],
      // 农资类型
      agriMateArr: [],
      sellOrderLIst: [],
      rightTableData: [],
      // addformData 添加的表单
      addformData: {},
      // 控制表格 添加行 input 显示隐藏
      addHide: true,
      purchaseVisible: false,
      dialogFormVisible: false,
      dialogFormVisibleTwo: false,
      endTime: "",
      startTime: "",
      titleText: "",
      startDatePickers: this.beginDates(),
      endDatePickers: this.processDates(),
      rules: {
        purchaseOrderNo: [
          { required: true, message: "请选择采购订单", trigger: "change" }
        ]
      },
      rulesTwo: {},
      buttonselectlist: [
        { name: "来料入库", value: 1 },
        { name: "自行入库", value: 0 }
      ],
      curTabIndex: 0,
      warehouseList: [],
      warehousingProductTypeList: ["成品", "半成品", "物料"],
      formDataTwo: {},
      warehousingSourceList: ["生产", "加工"],
      // 部门岗位员工列表
      departmentList: [],
      postList: [],
      staffList: []
    };
  },
  computed: {
    headers() {
      return {
        loginToken: sessionStorage.getItem("token"),
        organizationNo: sessionStorage.organizationNo,
        sysDataBaseName: sessionStorage.databaseName
      };
    }
  },
  watch: {
    rightTableData: {
      deep: true,
      handler(val) {
        let arr = [];
        val.forEach(item => {
          if (item.quantity && item.unitPrice) {
            arr.push(
              parseFloat(item.quantity) * parseFloat(item.unitPrice) -
                parseFloat(item.favorablePrice || "0")
            );
            item.totalPriceItem = (
              parseFloat(item.quantity) * parseFloat(item.unitPrice) -
              parseFloat(item.favorablePrice || "0")
            ).toFixed(2);
          } else {
            item.totalPriceItem;
          }
        });
        sum(arr);
        function sum(arr) {
          var s = 0;
          for (var i = arr.length - 1; i >= 0; i--) {
            s += arr[i];
          }
          return s;
        }
        this.totalPrice = sum(arr).toFixed(2) || 0;
        // console.log(sum(arr))
      }
    },
    addformData: {
      deep: true,
      handler(val) {
        // console.log(val)
        if (val.number && val.price) {
          // 当input值改变时计算
          this.$set(
            val,
            "totalPriceItem",
            (parseFloat(val.number) * parseFloat(val.price)).toFixed(2)
          );
        }
      }
    }
  },
  created() {
    this.queryDatalist();
  },
  mounted() {
    // 表格分页数据
    this.getTableDataList();
    this.getDepartmentList();
  },
  methods: {
    // 获取部门列表
    getDepartmentList() {
      managementtwo.getDepartmentList().then(res => {
        if (res.code !== 1) {
          return;
        }
        this.departmentList = res.data;
      });
    },
    getPostList(no) {
      managementtwo.getPostList(no).then(res => {
        if (res.code !== 1) {
          return;
        }
        this.postList = res.data;
      });
    },
    getStaffList(no) {
      managementtwo.getEmployeeList(no).then(res => {
        if (res.code !== 1) {
          return;
        }
        this.staffList = res.data;
      });
    },
    // 展示图片
    showimgmet(e) {
      if (e.pictureNoList && e.pictureNoList.length) {
        warehouseInventory
          .getWarehousingPicture(e.pictureNoList[0])
          .then(res => {
            this.nowimgurl = "data:image/png;base64," + res.data.pictureData;
            this.isshowimg = true;
          });
      } else {
        this.$message.warning("暂无图片");
      }
    },
    // 图片地址
    ImageUrl() {
      if (this.nowChanceStau === "edit" || this.nowChanceStau === "add") {
        let URL = `${baseURL.webServiceUrl}v3/warehouse/warehousingPicture/add`;
        return URL;
      } else {
        let URL = "#";
        // console.log(URL)
        return URL;
      }
    },
    handleResponse(response, file, fileList) {
      // return this.basicUrl + query/ + this.pictureNo
      this.pictureNo = response.data;
      warehouseInventory.getWarehousingPicture(this.pictureNo).then(res => {
        this.image = "data:image/png;base64," + res.data.pictureData;
      });
      return this.image;
    },
    handleRemove() {
      if (this.nowChanceStau === "edit") {
        // console.log(response);
        warehouseInventory.delWarehousingPicture(this.pictureNo).then(res => {
          if (res.code === 1) {
            delete this.pictureNo;
            delete this.formData.pictureNo;
            this.$message.success(res.msg);
          }
        });
      } else {
        return this.$message.error("点击修改按钮再进行编辑!");
      }
    },
    batchstaumet(index) {
      this.curTabIndex = index;
      this.getTableDataList();
    },
    // 获取 表格数据
    getTableDataList() {
      let param = {
        page: this.currentPage,
        size: this.pageSize,
        sort: "timestamp",
        entity: {
          ...this.searchInfo,
          warehousingOrderType: this.buttonselectlist[this.curTabIndex].value
        }
      };
      warehouseInventory.queryPageByConditionWarehouseOrder(param).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          // console.log(data);
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    async queryDatalist() {
      // 查询采购订单
      const { data: SellOrder } = await purchaseOrderManage.queryByCondition();
      this.sellOrderLIst = SellOrder;

      // // 查询客户名称
      // const { data: supplie } = await supplierManage.supplierName()
      // this.paramNamelist = supplie;
      // // 查询员工
      // const { data: Staff } = await StaffManage.getStaffListByCondition()
      // this.StaffData = Staff;
      // const { data: topitem } = await baseQuery.baseQueryByCondition()
      // // 查询农资名称
      // let topitemidList = topitem.map(item => item.farmingTypeNo)
      // const { data: agriMate } = await agriMateManage.queryAgriculturalList(topitemidList)
      // this.agriMateArr = agriMate;
    },
    async getWarehouseList() {
      // 查询仓库列表
      let params = {
        warehouseSystem: "生产",
        warehouseTypeName: this.formData.warehousingProductType
      };
      const {
        data: warehouseList
      } = await warehouseManage.getWareHouseListByCondition(params);
      this.warehouseList = warehouseList;
    },
    async getProductList(no) {
      // 查询入库产品列表
      const { data: dataList } = await purchaseOrderManage.queryByOrderNo(no);
      dataList.forEach(item => {
        item.favorablePrice = item.discountPrice;
        item.quantity = item.purchaseQuantity;
      });
      this.rightTableData = dataList;
    },
    async getGoodsList(type) {
      // eslint-disable-next-line eqeqeq
      if (type == "物料") {
        let res = await managementtwo.getqueryList({});
        this.goodsList = res.data;
      } else {
        let res = await productManage.queryByCondition({ productType: type });
        this.goodsList = res.data;
      }
    },
    // 搜索框时间
    startVal(e) {
      this.startTime = e;
    },
    endVal(e) {
      this.endTime = e;
    },
    beginDates() {
      const self = this;
      return {
        disabledDate(time) {
          if (self.formData.deliveryTime) {
            //  如果结束时间不为空，则小于结束时间
            return (
              new Date(self.formData.deliveryTime).getTime() < time.getTime()
            );
          } else {
            // return time.getTime() > Date.now()//开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },
    processDates() {
      const self = this;
      // if (self.endTime) {
      return {
        disabledDate(time) {
          if (self.formData.procurementTime) {
            //  如果开始时间不为空，则结束时间大于开始时间
            self.time = new Date();
            return (
              new Date(self.formData.procurementTime).getTime() > time.getTime()
            );
          } else {
            return time.getTime() > Date.now(); // 开始时间不选时，结束时间最大值小于等于当天
          }
        }
      };
    },

    selectRow(val) {
      this.selectlistRow = val;
    },
    // 点击添加按按钮
    addButInfo() {
      let list = {
        name: "",
        number: "",
        unitName: "",
        price: "",
        totalPriceItem: "",
        agriculturalMaterialId: ""
      };
      this.rightTableData.unshift(list);
      this.addformData = {};
    },
    // 删除改行
    deleteRow(index, rows) {
      rows.splice(index, 1);
    },
    selectable(row, index) {
      return row.status === true; // 通过某个值来进行判断，规定那一行的选择框被禁用
    },
    search() {
      this.currentPage = 1;
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },
    // 时间
    dateFormat(row, colnum) {
      if (row.deliveryTime) {
        return this.$moment(row[colnum.property]).format("YYYY-MM-DD HH:mm:ss");
      }
    },
    add() {
      this.rightTableData = [];
      this.canInput = true;
      this.nowChanceStau = "add";
      // eslint-disable-next-line eqeqeq
      if (this.curTabIndex == 0) {
        this.dialogFormVisible = true;
        this.formData = {};
      } else {
        this.dialogFormVisibleTwo = true;
        this.formDataTwo = {};
      }
    },
    async handledbCheck(row) {
      if (row.warehousingOrderNo) {
        this.formData = JSON.parse(JSON.stringify(row));
        let {
          data: warehousingGoodsList
        } = await warehouseInventory.getWarehousingGoodsByNo(
          row.warehousingOrderNo
        );
        this.rightTableData = warehousingGoodsList;
        this.purchaseVisible = true;
      }
    },
    handleSelectionChange(list) {
      this.purchaseOrderIdList = [];
      this.purchaseOrderIdList = list.map(item => item.purchaseOrderId);
      if (this.purchaseOrderIdList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          // eslint-disable-next-line eqeqeq
          if (this.curTabIndex == 0) {
            // 来料入库
            this.formData.totalPrice = this.totalPrice;
            this.formData.warehousingGoodsList = this.rightTableData;
            this.formData.organizationNo = sessionStorage.organizationNo;
            this.formData.pictureNoList = [this.pictureNo];
            warehouseInventory.addWarehousingOrder(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.dialogFormVisibleTwo = false;
                this.getTableDataList();
                // this.$refs[formData].resetFields()
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          } else {
            // 自行入库
            this.formDataTwo.totalPrice = this.totalPrice;
            this.formDataTwo.warehousingGoodsList = this.rightTableData;
            this.formDataTwo.organizationNo = sessionStorage.organizationNo;
            this.formDataTwo.pictureNoList = [this.pictureNo];
            // console.log(this.formData);
            warehouseInventory
              .addWarehousingOrder(this.formDataTwo)
              .then(res => {
                if (res.code === 1) {
                  this.$message.success(res.msg || "新增成功！");
                  // this.$refs[formDataTwo].resetFields()
                  this.getTableDataList();
                  this.dialogFormVisibleTwo = false;
                } else {
                  this.$message.error(res.msg || "新增失败！");
                }
              });
          }
        }
      });
    },
    handleClose(done) {
      this.resetActionBar();
      done();
    },
    cancelTwo() {
      this.dialogFormVisibleTwo = false;
    },
    tableAgriMate(scope) {
      let obj = {};
      // eslint-disable-next-line eqeqeq
      if (this.formDataTwo.warehousingProductType == "物料") {
        // eslint-disable-next-line eqeqeq
        obj = this.goodsList.find(item => item.materialNo == scope.row.goodsNo);
        obj.goodsName = obj.materialName;
        obj.goodsNo = obj.materialNo;
      } else {
        // eslint-disable-next-line eqeqeq
        obj = this.goodsList.find(item => item.productNo == scope.row.goodsNo);
        obj.goodsName = obj.productName;
        obj.goodsNo = obj.productNo;
      }
      this.$set(this.rightTableData, scope.$index, obj);
    },

    handleDelete(row) {
      // warehouseInventory.delWarehousingOrder(row.warehousingOrderNo).then(res => {
      //   if (res.code === 1) {
      //     this.$message.success(res.msg);
      //     this.getTableDataList();
      //   } else {
      //     this.$message.warning(res.msg || '删除失败');
      //   }
      // });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          warehouseInventory
            .delWarehousingOrder(row.warehousingOrderNo)
            .then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg);
                this.getTableDataList();
              } else {
                this.$message.warning(res.msg || "删除失败");
              }
            });
        })
        .catch(() => {
          //
          this.$message("取消删除");
        });
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
::v-deep .el-row {
  .el-table__header-wrapper {
    position: inherit !important;
  }
  .el-table__body-wrapper {
    margin-top: 0 !important;
  }
}
.search-item {
  display: flex;
  height: 36px;
  margin-left: 20px;
  white-space: nowrap;
  &:first-child {
    margin: 0;
  }
  span {
    display: inline-block;
  }
  &.rules-wrap span {
    padding: 0 15px;
    border: 1px solid $borderColor;
    cursor: pointer;
    line-height: 35px;
    transition: border-color 0.2s;
    box-sizing: border-box;
    &:hover {
      border-color: #6ecae3;
    }
  }
}
.purchase {
  ::v-deep .el-dialog {
    border: 1px solid #000;
    border-radius: 10px;
    .el-dialog__header {
      border-radius: 9px 9px 0 0;
      .el-dialog__title {
        color: #fff;
      }
    }
    .el-dialog__body {
      padding: 5px 20px;
      font-size: 12px !important;
      .el-input {
        input {
          font-size: 12px;
        }
      }
    }
    .el-table {
      max-height: 200px;
      overflow-y: auto;
      background-color: rgba(255, 255, 255, 1);
      .cell {
        color: #000;
      }
      th {
        background-color: rgba(230, 230, 230, 1);
      }
      th.is-leaf {
        border-color: rgba(77, 77, 77, 1);
      }
      td {
        border-color: rgba(77, 77, 77, 1);
      }
      tr:hover {
        background-color: rgba(77, 77, 77, 1);
      }
      .el-table__empty-text {
        color: #000;
      }
      .current-row {
        // background-color: rgb(177, 177, 177);
        background-color: #dbdbdb !important;
      }
      .el-table__row--striped {
        background-color: rgba(255, 255, 255, 1);
      }
      // color: #000;
    }
    .el-table--border {
      border-color: rgba(77, 77, 77, 1);
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .el-table--enable-row-hover .el-table__body tr:hover > td {
      background-color: rgb(177, 177, 177);
    }
    .el-table__body tr.current-row > td {
      background-color: #dbdbdb !important;
    }
    .el-form-item {
      margin-bottom: 10px;
    }
    .total-price {
      color: #000;
    }
    .el-table__body {
      // height: ;
      height: 0;
      // background-color: #003947;
    }
  }
}
.el-date-editor,
.el-select {
  width: 100%;
}

h4.total-price {
  display: flex;
  justify-content: space-between;
  margin: 0;
  color: #fff;
  margin-bottom: 5px;
}

.right-table {
  line-height: 0px;
}
.addInfo {
  width: 100%;
}
.rightTableData {
  // .
  ::v-deep .el-table--border {
    border: #5fb6cd;
  }
  ::v-deep .cell {
    margin: 0 !important;
    // padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
  ::v-deep .el-table--medium th {
    margin: 0 !important;
    padding: 0 !important;
    font-size: 10px;
  }
}
.total {
  ::v-deep .el-input__inner {
    border-right: 1px solid #6ecae3 !important;
  }
}
::v-deep .el-dialog__wrapper {
  .el-dialog {
    // width: 70% !important;
    .el-select {
      width: 100% !important;
    }
    .el-dialog__body {
      .el-form {
        .el-row {
          .el-table {
            max-height: 267px !important;
            .el-table__header-wrapper {
              position: fixed;
              z-index: 99;
            }
            .el-table__body-wrapper {
              margin-top: 38px;
            }
          }
        }
      }
    }
  }
}
</style>
